﻿@page "/JavaEnum"
@using JavaDevToys.Rcl.Models
@using JavaDevToys.Rcl.Service

<MAlert Dismissible
        Type="AlertTypes.Error"
        @bind-Value="_alert">
    @errMsg
</MAlert>
<MDialog
    @bind-Value="dialog"
    Width="700">
    <ChildContent>
        <MCard>
            <MCardTitle Class="text-h5 grey lighten-2">
                结果
            </MCardTitle>
            <MTextarea Clearable
                ClearIcon="mdi-close-circle"
                Label="代码"
                @bind-Value="JavaParameterResult">
            </MTextarea>

            <MDivider></MDivider>

            <MCardActions>
                <MSpacer></MSpacer>
                <MButton Color="primary" Class="mt-2  ml-9" OnClick="CopyJavaParameter">复制结果</MButton>
                <MButton
                    Color="primary"
                    Text
                    OnClick="() => dialog = false">
                    关闭
                </MButton>
            </MCardActions>
        </MCard>
    </ChildContent>
</MDialog>
<MDialog
    @bind-Value="dialog_code"
    Width="400">
    <ChildContent>
        <MCard>
            <MCardTitle Class="text-h5 grey lighten-2">
                请输入类名(不以Enum结尾)
            </MCardTitle>
            <MTextField @bind-Value="@className" FullWidth="false" class="ml-2 mr-2"
                        Hint="This field used your class name"
                        Label="类名">
            </MTextField>

            <MDivider></MDivider>

            <MCardActions>
                <MSpacer></MSpacer>
                <MButton Color="primary" Class="mt-2  ml-9" OnClick="CreateJavaEnum">确定</MButton>
                <MButton
                    Color="primary"
                    Text
                    OnClick="() => dialog_code = false">
                    关闭
                </MButton>
            </MCardActions>
        </MCard>
    </ChildContent>
</MDialog>
<h3>枚举生成</h3>
<MContainer Fluid>
    <MRow Align="@AlignTypes.Center">
        <MCol Cols="6">
            <div class="d-flex pt-6">
                <MSelect Items="settingInfo.JavaProjectInfoList"
                         @bind-Value="@selectedJavaProjectName"
                         ItemText="u => u.Desc"
                         ItemValue="u => u.Name"
                         MinWidth="140"
                         Filled
                         Label="选择工程"
                         FullWidth="false"
                         Dense>
                </MSelect>
                <MSelect Items="folderList"
                         @bind-Value="@selectedFolder"
                         ItemText="u=>u"
                         ItemValue="u=>u"
                         MinWidth="300"
                         Filled
                         Label="输出文件夹"
                         FullWidth="false"
                         Dense
                         Clearable
                         Class="ml-6">
                </MSelect>
                <MButton Color="primary" Class="mt-2  ml-9" OnClick="CreateJavaEnum" Disabled="canCreateJava">生成枚举</MButton>
                <MButton Color="primary" Class="mt-2  ml-9" OnClick="CreateJavaEnumCode" Disabled="canCreateCode">生成代码</MButton>
            </div>
        </MCol>
    </MRow>
    <MRow Align="@AlignTypes.Center">
        <MList>
            @if (outFilePathList != null)
            {
                <MButton Color="primary" Class="mt-2  ml-9" OnClick="AddGit">添加到git</MButton>
                @foreach (var item in outFilePathList)
                {
                    <MListItem>
                        <MListItemAction>
                            <MIcon>@item.Value</MIcon>
                        </MListItemAction>
                        <MListItemContent>
                            <MListItemTitle>@item.Key</MListItemTitle>
                        </MListItemContent>
                    </MListItem>
                }
            }
        </MList>
    </MRow>
    <MRow Align="@AlignTypes.Center">
        <MCol>
            @if (!string.IsNullOrWhiteSpace(searchCodeSystem) || (dictCodeSystems != null && dictCodeSystems.Count() > 0))
            {
                <MDataTable @bind-selected="selectedDictCodeSystems"
                            TItem="DictCodeSystem"
                            Headers="_dictCodeSystemHeaders"
                            Items="dictCodeSystems"
                            SingleSelect=false
                            Height="200"
                            FixedHeader="true"
                            ItemKey="r => r.codeSystemId.ToString()"
                            ShowSelect
                            Class="elevation-1">
                    <TopContent>
                        <MToolbar Class="mb-2"
                                  Color="indigo darken-9"
                                  Dark
                                  Flat>
                            <MToolbarTitle>编码体系</MToolbarTitle>
                            <MTextField @bind-Value="searchCodeSystem"
                                        Label="输入(编码、名称、拼音、五笔)进行检索"
                                        Class="pl-4 mt-4"></MTextField>
                        </MToolbar>
                    </TopContent>
                </MDataTable>
            }
        </MCol>
    </MRow>
    <MRow Align="@AlignTypes.Center">
        <MCol>
            @if (!string.IsNullOrWhiteSpace(_searchDataSets) || (dictDataSets != null && dictDataSets.Count() > 0))
            {
                <MDataTable @bind-selected="selectedDictDataSets"
                            TItem="DictDataSets"
                            Headers="_dictDataSetsHeaders"
                            Items="dictDataSets"
                            SingleSelect=false
                            FixedHeader="true"
                            Height="250"
                            ItemKey="r => r.dataValueId.ToString()"
                            Search="@_searchDataSets"
                            ShowSelect
                            Class="elevation-1">
                    <TopContent>
                        <MToolbar Class="mb-2"
                                  Color="indigo darken-9"
                                  Dark
                                  Flat>
                            <MToolbarTitle>值集</MToolbarTitle>
                            <MTextField @bind-Value="_searchDataSets"
                                        Label="输入(编码、名称)进行过滤"
                                        Class="ml-4 mt-4"></MTextField>
                        </MToolbar>
                    </TopContent>
                </MDataTable>
            }
        </MCol>
    </MRow>
</MContainer>
@code {
    private bool _alert = false;
    private string errMsg = string.Empty;
    private bool dialog=false;
    private bool dialog_code = false;
    private bool canCreateJava => selectedDictCodeSystems.Count()==0;
    private bool canCreateCode => selectedDictDataSets.Count()==0;
    private bool canAddGit => outFilePathList == null || outFilePathList.Count() == 0;
    private string _selectedJavaProjectName;
    private string selectedJavaProjectName
    {
        get => _selectedJavaProjectName;
        set {
            _selectedJavaProjectName = value;
            SelectedJavaProjectChange(_selectedJavaProjectName);
        }
    }
    private SettingInfo settingInfo;
    private string selectedFolder;
    private List<string> folderList=new List<string>();
    private string _searchCodeSystem="";
    private string searchCodeSystem
    {
        get => _searchCodeSystem;
        set
        {
            _searchCodeSystem = value;
            FilterCodeSystem();
        }
    }
    private IEnumerable<DataTableHeader<DictCodeSystem>> _dictCodeSystemHeaders = new List<DataTableHeader<DictCodeSystem>>()
    {
        new()
        {
            Text = "编码体系NO",
            Align = DataTableHeaderAlign.Start,
            Sortable = false,
            Value = nameof(DictCodeSystem.codeSystemNo)
        },
        new() { Text = "名称", Value = nameof(DictCodeSystem.codeSystemName) },
        new() { Text = "描述", Value = nameof(DictCodeSystem.description) },
        new() { Text = "版本", Value = nameof(DictCodeSystem.version) },
        new() { Text = "来源名称", Value = nameof(DictCodeSystem.sourceName) },
    };

    private IEnumerable<DictCodeSystem> dictCodeSystems = new List<DictCodeSystem>();
    private IEnumerable<string> _selectedDictCodeSystems = new List<string>();
    private IEnumerable<string> selectedDictCodeSystems
    {
        get => _selectedDictCodeSystems;
        set
        {
            _selectedDictCodeSystems = value;
            OnSelectedDictCodeSystemsChanges(_selectedDictCodeSystems);
        }
    }
    private string _searchDataSets;
    private List<DataTableHeader<DictDataSets>> _dictDataSetsHeaders = new()
    {
        new()
        {
            Text = "值编码",
            Align = DataTableHeaderAlign.Start,
            Sortable = false,
            Value = nameof(DictDataSets.dataValueNo)
        },
        new() { Text = "名称", Value = nameof(DictDataSets.dataValueCnName) },
        new() { Text = "描述", Value = nameof(DictDataSets.dataValueDescription) },
    };
    private IEnumerable<DictDataSets> dictDataSets = new List<DictDataSets>();
    private IEnumerable<string> selectedDictDataSets = new List<string>();
    [Inject]
    public IJavaServiceParser javaServiceParser { get; set; }
    [Inject]
    public IJavaCodeGenerator javaCodeGenerator { get; set; }
    [Inject]
    public IApiInfoParser apiInfoParser { get; set; }
    [Inject]
    public IJavaProjectService javaProjectService { get; set; }
    [Inject]
    public IDirectoryPicker directoryPicker { get; set; }
    [Inject]
    public ISettingService settingService { get; set; }
    [Inject]
    public IJavaEnumParser javaEnumParser { get; set; }
    [Inject]
    public IClipboardService clipboardService { get; set; }
    private Dictionary<string, string> outFilePathList;
    private string JavaParameterResult;
    private string className;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        settingInfo = settingService.GetSettings(0);
    }

    private void SelectedJavaProjectChange(string javaProjectName)
    {
        if (string.IsNullOrWhiteSpace(javaProjectName))
            return;
        JavaProjectInfo javaProjectInfo = settingInfo.JavaProjectInfoList.FirstOrDefault(f => f.Name == selectedJavaProjectName);
        if (javaProjectInfo == null)
            return;
        if (string.IsNullOrWhiteSpace(javaProjectInfo.FullPath))
        {
            errMsg = "项目路径未设置，请点击右上角设置按钮进行设置";
            _alert = true;
            return;
        }
        if (string.IsNullOrWhiteSpace(javaProjectInfo.sqlserverInfo.Database))
        {
            errMsg = "数据库连接未设置，请点击右上角设置按钮进行设置";
            _alert = true;
            return;
        }
        try
        {
            //找到enums文件夹下的所有文件夹
            folderList=directoryPicker.GetFolderDirectories(directoryPicker.SearchDirectory(javaProjectInfo.FullPath, "enums"));
            //查询编码体系
            dictCodeSystems = javaEnumParser.QueryCodeSystem(javaProjectInfo, _searchCodeSystem);
            StateHasChanged();
        }
        catch (Exception ex)
        {
            errMsg = ex.Message;
            _alert = true;
            return;
        }

    }

    private void OnSelectedDictCodeSystemsChanges(IEnumerable<string> dictCodeSystems)
    {
        if (dictCodeSystems.Count() == 0)
        {
            dictDataSets = new List<DictDataSets>();
            return;
        }
        JavaProjectInfo javaProjectInfo = settingInfo.JavaProjectInfoList.FirstOrDefault(f => f.Name == selectedJavaProjectName);
        dictDataSets = javaEnumParser.QueryDataSetsByCodeSystemIds(javaProjectInfo, dictCodeSystems.Select(s => long.Parse(s)));
    }

    private void FilterCodeSystem()
    {
        selectedDictCodeSystems = new List<string>();
        JavaProjectInfo javaProjectInfo = settingInfo.JavaProjectInfoList.FirstOrDefault(f => f.Name == selectedJavaProjectName);
        dictCodeSystems = javaEnumParser.QueryCodeSystem(javaProjectInfo, _searchCodeSystem);
    }

    private void CreateJavaEnum()
    {
        dialog_code = false;
        JavaProjectInfo javaProjectInfo = settingInfo.JavaProjectInfoList.FirstOrDefault(f => f.Name == selectedJavaProjectName);
        if (javaProjectInfo == null)
        {
            errMsg = "请选择工程项目";
            _alert = true;
            return;
        }
        if (string.IsNullOrWhiteSpace(javaProjectInfo.FullPath))
        {
            errMsg = "项目路径未设置，请点击右上角设置按钮进行设置";
            _alert = true;
            return;
        }
        if (string.IsNullOrWhiteSpace(javaProjectInfo.sqlserverInfo.Database))
        {
            errMsg = "数据库连接未设置，请点击右上角设置按钮进行设置";
            _alert = true;
            return;
        }
        if (selectedDictCodeSystems.Count() <= 0)
        {
            errMsg = "未选择编码体系，请选择!";
            _alert = true;
            return;
        }
        if (dictCodeSystems.Any(a => selectedDictCodeSystems.Contains(a.codeSystemId.ToString()) && !a.codeSystemNo.Contains('_')))
        {
            if (selectedDictCodeSystems.Count() > 1)
            {
                errMsg = "选择的编码体系包含不能自动生成类名的字段，请单选并指定类名!";
                _alert = true;
                return;
            }
            if (string.IsNullOrWhiteSpace(className))
            {
                dialog_code = true;
                return;
            }
            else
            {
                foreach (var item in dictCodeSystems.Where(w => selectedDictCodeSystems.Contains(w.codeSystemId.ToString())))
                {
                    item.codeSystemNo = className;
                }
                className = string.Empty;
            }
        }
        // 生成Java类
        var pathList = javaCodeGenerator.GenerateEnum(javaProjectInfo, dictCodeSystems.Where(w => selectedDictCodeSystems.Contains(w.codeSystemId.ToString())), dictDataSets, selectedFolder);
        outFilePathList = new Dictionary<string, string>();
        foreach (var item in pathList)
        {
            outFilePathList.Add(item, "mdi-label");
        }
    }

    private void CreateJavaEnumCode()
    {
        if (selectedDictDataSets.Count()<=0)
        {
            errMsg = "请选择值集!";
            _alert = true;
            return;
        }
        JavaParameterResult = javaCodeGenerator.GenerateEnumCode(dictDataSets.Where(w=>selectedDictDataSets.Contains(w.dataValueId.ToString())));
        dialog = true;
    }

    private void AddGit()
    {
        foreach (var item in outFilePathList)
        {
            if (javaProjectService.AddGitRepository(item.Key, out string errMsg))
            {
                outFilePathList[item.Key] = "mdi-check";
            }
        }
    }

    private void CopyJavaParameter()
    {
        clipboardService.SetTextAsync(JavaParameterResult);
    }
}
